package com.yl.util;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.yl.ifanr.service.BaseService;

public class NetDataLoader {
	private static final String TAG = "NetDataLoader";
	private BlockingQueue queue;
	public static ThreadPoolExecutor executor;
	
	public NetDataLoader(){
		// 线程池：最大50条，每次执行：1条，空闲线程结束的超时时间：180秒
   	 queue = new LinkedBlockingQueue();
   	 executor = new ThreadPoolExecutor(2, 50, 180, TimeUnit.SECONDS, queue);
	}
	/**
     * 访问服务器接口
     * @param baseSevice
     * @param dataCallback
     */
    public void loadData(final BaseService baseSevice,final DataCallback dataCallback) {

        final Handler handler = new Handler() {
            public void handleMessage(Message message) {
            		dataCallback.dataLoaded((BaseService) message.obj);
            }
        };
        
        executor.execute(new Runnable() {
            @Override
            public void run() {
           	try {
           		boolean result = baseSevice.updateData();
           		Message message = handler.obtainMessage(0, baseSevice);
           		handler.sendMessage(message);
				} catch (Exception e) {
					// TODO: handle exception
					Log.e("NetDataLoader:", e.getMessage());
				}
                
            }
        });
    }
    /**
     * 更新完数据后的回调接口
     * @author hhq163
     *
     */
    public interface DataCallback {
        public void dataLoaded(BaseService baseService);
    }
}
